package db

import (
	"database/sql"
	"fmt"
	"time"

	stdcontext "context"

	"github.com/qf-tech/qftech-base/pkg/log"

	_ "github.com/go-sql-driver/mysql"
	"github.com/uptrace/bun"
	"github.com/uptrace/bun/dialect/mysqldialect"
)

type QueryHook struct{}

func (h *QueryHook) BeforeQuery(ctx stdcontext.Context, event *bun.QueryEvent) stdcontext.Context {
	return ctx
}

func (h *QueryHook) AfterQuery(ctx stdcontext.Context, event *bun.QueryEvent) {
	log := log.GetLogger().GetCtx(ctx).Sugar()
	log.Infof("time: %v, query: %s", time.Since(event.StartTime), string(event.Query))
}

var BunDb *bun.DB

type DBConfig struct {
	Username string
	Password string
	Host     string
	Port     int
	DBName   string
}

// Init def
func Init(config DBConfig) error {
	var err error

	dbInfo := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8",
		config.Username,
		config.Password,
		config.Host,
		config.Port,
		config.DBName)

	sqldb, err := sql.Open("mysql", dbInfo)
	if err != nil {
		panic(err)
	}

	BunDb = bun.NewDB(sqldb, mysqldialect.New())

	//https://bun.uptrace.dev/guide/hooks.html#query-hooks
	BunDb.AddQueryHook(&QueryHook{})
	return nil
}
